﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

namespace RabbitMQ
{
    public class MessageQueueManager
    {
        private readonly string _hostName;
        private readonly int _port;
        private readonly string _userName;
        private readonly string _password;
        private readonly string _queueName;

        public MessageQueueManager(string hostName, int port, string userName, string password, string queueName)
        {
            _hostName = hostName;
            _port = port;
            _userName = userName;
            _password = password;
            _queueName = queueName;
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        public void SendMessage(string message)
        {
            var factory = new ConnectionFactory()
            {
                HostName = _hostName,
                Port = _port,
                UserName = _userName,
                Password = _password
            };

            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(_queueName, true, false, false, null);

                var body = Encoding.UTF8.GetBytes(message);
                channel.BasicPublish("", _queueName, null, body);
                Console.WriteLine("Sent message: {0}", message);
            }
        }
        public async Task ReceiveMessage()
        {
            var factory = new ConnectionFactory()
            {
                HostName = _hostName,
                Port = _port,
                UserName = _userName,
                Password = _password
            };

            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(_queueName, true, false, false, null);

                var resetEvent = new ManualResetEvent(false);
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (sender, eventArgs) =>
                {
                    var receivedMessage = Encoding.UTF8.GetString(eventArgs.Body.ToArray());
                    Console.WriteLine("Received message: {0}", receivedMessage);

                    resetEvent.Set(); // 接收到消息后设置 ManualResetEvent
                };

                channel.BasicConsume(_queueName, true, consumer);
                Console.WriteLine("Waiting for messages...");

                await Task.Run(() => resetEvent.WaitOne()); // 阻塞当前线程，直至 ManualResetEvent 被设置
            }
        }
    }
}
